<?php
header("Content-Type:text/html;charset=utf-8");
$searchkey = "";
if (empty($_POST))
    $searchkey = "";
else
    $searchkey = $_POST["skey"];

?>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <form action="/4.php" method="post">
        <input type="text" name="skey" id="skey" value="<? echo $searchkey ?>"/>
        <input type="submit" value="submit"/>
    </form>
<?php

if (empty($searchkey)) exit();
$data = Search($searchkey);
echo "共有多少个结果" . count($data) . "<br />";


$pdata=array();


foreach ($data as $k => $v) {


    // echo $v."<hr />\n\n\n\n\n";
    preg_match_all('/<h3[\s\S]*?(<a[\s\S]*?<\/a>)/', $v, $rs_t);
    $title = $rs_t[0][0];
    $title = preg_replace("/<[\S\s]+?>/", "", $title);

    $urlreg = '/\<span class=\"(g|c-showurl)\"[\S\s]{5,100}?\<\/span\>/';

    //echo $title ."<hr />\n\n\n\n\n";

    preg_match_all($urlreg, $v, $urls);
    //  print_r($urls)."<br />";

    $len = count($urls[0]);
    if (!$len) {
        $urlreg = '/color="#008000">[\S\s]+?<span/';
        preg_match_all($urlreg, $v, $urls);
        $urls[0][0] = $urls[0][0] . ">";
    }
    $siteurl = $urls[0][0];
    $siteurl = cleanurl($siteurl);


    //print_r($rs_t);
    //echo "\n\n\n<hr />";
    $template="title is:%s --url is:%s<br />";

    echo sprintf($template,$title,$siteurl);

    $titleurl=array("title"=>$title,"siteurl"=>$siteurl);
    $pdata[]=$titleurl;

}


//print_r($pdata);


function cleanurl($siteurl)
{

    $furlreg = '/\>[\s\S]+?\</';
    preg_match($furlreg, $siteurl, $furls);
    $siteurl = $furls[0];
    $siteurl = preg_replace('/\d{4}-\d{1,2}-\d{1,2}/', '', $siteurl);
    $siteurl = str_replace(">", "", $siteurl);
    $siteurl = str_replace("<", "", $siteurl);
    $siteurl = str_replace("&nbsp;", "", $siteurl);
    return $siteurl;
}


function Search($keyword)
{
    $enKeyword = urlencode($keyword);
    $url1 = "http://www.baidu.com/s?wd=$enKeyword&rn=50"; //鏋勯€燝ET URL
    $contents = file_get_contents($url1);
    preg_match_all('/<table[^>]*?class="result[^>]*>[\s\S]*?<\/table>/i', $contents, $rs);
    return $rs[0];
}

?>